import React, {useState,useEffect} from 'react'
import { List, Skeleton,Pagination,Button, message  } from 'antd';
import {ArticleListApi,ArticleDeiApi} from '../request/api'
import {useNavigate} from 'react-router-dom'
import moment from 'moment';


export default function ListList() {

  const [updateone,setUpdateone] = useState(1)
  const [list,setList] = useState([])
  const [total,setTotal] = useState(0)
  const [current,setCurrent] = useState(1)
  const [pageSize,setPageSize] = useState(10)
  const navigate = useNavigate()

  //请求封装
  const getList = (num)=>{
    ArticleListApi({
      num,
      count:pageSize
    }).then(res=>{
      console.log(res.data.arr);
      if(res.errCode===0){
        let {arr,count,num,total} = res.data;
        setList(arr);
        setTotal(total);
        setCurrent(num);
        setPageSize(count);
      }
    })
  }

  //请求列表数据 模拟componentDidMount
  useEffect(()=>{
    // ArticleListApi({
    //   num:current,
    //   count:pageSize
    // }).then(res=>{
    //   console.log(res.data.arr);
    //   if(res.errCode===0){
    //     let {arr,count,num,total} = res.data;
    //     setList(arr);
    //     setTotal(total);
    //     setCurrent(num);
    //     setPageSize(count);
    //   }
    // })
    getList(current)
  },[])

  //专门检测删除 模拟componentDidUpdate
  useEffect(()=>{
    getList(current)
  },[updateone])

  //分页时请求数据列表
  const onChange = (pages)=>{
    // console.log(pages);
    // setCurrent(pages);
    getList(pages);
  }

  //删除按钮
  const delFn = (id)=>{
    console.log(id);
    //得到id后删除
    ArticleDeiApi({id}).then(res=>{
      console.log(res);
      if(res.errCode===0){
        //提示删除成功
        message.success(res.message)
        //要么重新刷新页面，要么重新请求数据 或者直接window.reload，还有调用上面getList(1);
        //或者增加变量的监测
        setUpdateone(updateone+1)
      }
    })
  }


  return (
    <div className='list_table' style={{padding:'20px'}}>
      <List
      className="demo-loadmore-list"
      itemLayout="horizontal"
      dataSource={list}
      renderItem={(item) => (
        <List.Item
          actions={[
            <Button type='primary' onClick={()=>navigate('/edit/'+item.id)}>编辑</Button>, 
            <Button type='danger' onClick={()=>delFn(item.id)}>删除</Button>
        ]}
        >
          <Skeleton loading={false}>
            <List.Item.Meta
              title={<a href="!#">{item.title}</a>}
              description={item.subTitle}
            />
            <div>{moment(item.date).format("YYYY-MM-DD hh:mm:ss")}</div>
          </Skeleton>
        </List.Item>
      )}
    />
    {/* 分页按钮 */}
    <Pagination 
    onChange={onChange} 
    current={current} 
    pageSize={pageSize} 
    total={total}
    style={{float: 'right',marginTop: '20px'}}
     />
    </div>
  )
}
